<?php


namespace common\services;


use common\helpers\Aes;
use Yii;
use yii\web\Response;

class AesSignService
{

    /**
     * 验证aes签名
     * @param $data
     * @param string $key
     * @return bool
     */
    public static function checkSign($data, $key = 'aes_h5_key')
    {
        try {
            if (empty($data['sign'])) {
                throw new \Exception('缺少签名信息sign', '404');
            }

            if(YII_ENV_DEV) return true;

            //获取签名数据并转码
            $sign = base64_decode($data['sign']);

            if (empty($data)) {
                throw new \Exception('缺少参数信息', '404');
            }

            $localSign = self::setSign($data,false, $key);

            return $sign == $localSign;

        } catch (\Exception $e) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            Yii::$app->response->data = [
                'status' => $e->getCode(),
                'message' => $e->getMessage() . ' at file ' . __FILE__,
            ];
            return false;
        }
    }


    /**
     * 生成签名
     * @param $data
     * @param bool $baseEncode
     * @param string $key
     * @return string
     */
    public static function setSign($data, $baseEncode = false, $key = 'aes_h5_key')
    {
        unset($data['sign']);
        ksort($data);
        //aes加密盐
        $key = Yii::$app->params[$key];
        //将参数序列化为字符串格式
        $dataStr = rsa_encode($data);
        $aesClient = new Aes($key);
        $sign = $aesClient->encrypt($dataStr);
        if ($baseEncode) $sign = base64_encode($sign);
        return $sign;
    }
}